<template>
  <div class="container">
    <el-row style="height:100%;">
      <el-col :span="6" style="height:100%;">
        <div class="tree-container">
          <h3>仓库</h3>
          <el-input placeholder="输入仓库名称进行过滤" v-model="treeFilter" class="tree-filter"/>
          <el-tree
            ref="tree"
            highlight-current
            default-expand-all
            node-key="id"
            :expand-on-click-node="false"
            :data="treeData"
            :props="defaultProps"
            :filter-node-method="handleTreeFilter"
            @node-click="handleTreeNodeClick"
          />
        </div>
      </el-col>
      <el-col :span="18">
        <DataView
          ref="dataView"
          propViewKey="wm_stock_safety"
          propViewForm="wm/stock-safety/detail.vue"
          :propInitData="selectedTreeNode"
        />
      </el-col>
    </el-row>
  </div>
</template>

<script>
import DataView from '@/components/DataView.vue'

export default {
  name: 'stocksatety',
  data() {
    return {
      treeData: [],
      treeFilter: '',
      selectedTreeNode: {},
      treeEntry: '/base/warehouse/list',
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  created() {
    this.loadTree()
  },
  components: {
    DataView
  },
  watch: {
    treeFilter(val) {
      this.$refs.tree.filter(val)
    }
  },
  methods: {
    loadTree() {
      let that = this
      this.$ajax.get(this.treeEntry, {}).then(response => {
        if (response.code == 0) {
          //没有树结构，构造parentId
          response.data.forEach(item => item.parentId = 0)
          that.treeData = global.utils.convertToTree(response.data, {
            keyFieldName: 'id',
            rootNode: {id: 0,
              parentId: -1,
              name: '全部' },
            parentFieldName: 'parentId',
            labelFieldName: 'name'
          })
          if (!that.selectedTreeNode.id) {
            that.selectedTreeNode = that.treeData[0]
          }
          this.$nextTick(() => {
            that.$refs.tree.setCurrentKey(that.selectedTreeNode.id)
          })
        } else {
          that.utilMessage.error(response.msg)
        }
      })
    },
    handleTreeNodeClick(data) {
      this.selectedTreeNode = data
      let queryWrapper = data.id == 0 ? this.$newWrapper() : this.$newWrapper().eq('warehouseId', data.id)
      this.$refs.dataView.setQueryWrapper(queryWrapper)
    },
    handleTreeFilter(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    }
  }
}
</script>

<style lang="scss" scoped>
  .container {
    height: 100%;
    background-color: #fff;
  }
  .tree-container {
    padding:10px;
    margin-right:20px;
    border:solid 1px #DCDFE6;
    height:100%
  }
  .tree-filter {
    margin:10px;
    width:80%
  }
</style>
